const connection = require('../app/database')

class CommentService {
	async create(content, post_id, user_id) {
		console.log(content, post_id, user_id)
		const statement =
			'INSERT INTO comments (content, post_id, user_id) VALUES (?, ?, ?);'
		const [result] = await connection.execute(statement, [
			content,
			post_id,
			user_id
		])
		console.log(result)
		return result
	}

	async reply(content, post_id, parent_id, user_id) {
		const statement =
			'INSERT INTO comments (content, post_id, parent_id, user_id) VALUES (?, ?, ?, ?);'
		const [result] = await connection.execute(statement, [
			content,
			post_id,
			parent_id,
			user_id
		])
		return result
	}

	async searchComment(post_id) {
		const [comments] = await connection.execute(
			`
    	SELECT c.*,u.name,up.avatar_url FROM comments c
			LEFT JOIN users u
			ON c.user_id = u.id
			LEFT JOIN user_profiles up
			ON u.id = up.user_id
			WHERE post_id = ? 
			ORDER BY created_at ASC
  	`,
			[post_id]
		)
		return comments
	}

	async removeComment(comment_id) {
		const statement = `DELETE FROM comments WHERE id = ?`
		const [result] = await connection.execute(statement, [comment_id])
		return result
	}
}
module.exports = new CommentService()
